package com.hongshan.wallet.core.wallet

import android.app.Application
import android.databinding.ObservableField
import android.view.View
import com.hongshan.wallet.Constant
import com.hongshan.wallet.MyApplication
import com.hongshan.wallet.R
import com.hongshan.wallet.base.MyViewModel
import com.hongshan.wallet.base.SingleLiveEvent
import com.hongshan.wallet.bean.BindInfoBean
import com.hongshan.wallet.http.HttpClient
import com.hongshan.wallet.router.RouterIndex
import com.hongshan.wallet.router.go
import com.hongshan.wallet.toast
import com.hongshan.wallet.tryRun
import com.hongshan.wallet.util.AutoInject
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.launch

/**
 * Copyright Zhangxx.
 * Copyright (c) 2019
 * All rights reserved
 *
 * @project  : Wallet
 * @package  : com.example.wallet.core.wallet
 * @author   : zhangxx
 * @date     : 2019/3/26
 * @email    : qq957413212@hotmail.com
 * @desc     : //TUDO
 */
class BindAccountViewModel(application: Application) :MyViewModel(application) {

    val accountType = ObservableField<String>("姓名")

    val account = ObservableField<String>("")

    val accountEnable = ObservableField(true)

    val canOption = ObservableField(true)

    val statusStr = ObservableField<String>("账户停用")

    val bindButton = ObservableField<String>("确认绑定")

    val showAlert = ObservableField(false)

    val onLineStatus = ObservableField<Int>(R.drawable.ic_switch_o)

    val openGalley = SingleLiveEvent<Unit>()

    var qrCode: String? = null

    val showAlipayAuthor = ObservableField(false)

    val type = ObservableField(0)

    val bankName = ObservableField("")

    val name = ObservableField("")

    val alipayBindStatus = ObservableField<Boolean>(true)

    val author = View.OnClickListener {
        go(RouterIndex.WEB, mapOf("url" to "${Constant.HttpApi.BASE_URL}/index/auth/aliBind?token=${MyApplication.user?.token}"))
    }

    val text = ObservableField("请确认绑定微信为您本人账号\n且真实有效")

    @AutoInject(Constant.ROUTE_PARAMS_KEY.BIND_ACCOUNT_DATA)
    var accountBean: BindInfoBean? = null

    val changeStatus = View.OnClickListener {
        val isOnline = onLineStatus.get() == R.drawable.ic_switch_o
        GlobalScope.launch(Dispatchers.Main) {
            val result = GlobalScope.async(Dispatchers.IO) {
                tryRun {
                    HttpClient.httpApi.changeBindStatus(accountBean!!.account_type, if (isOnline) 0 else 1)
                        .execute()
                }
            }
            val body = result.await()?.body()
            if (body?.code == 0) {
                if (isOnline) {
                    onLineStatus.set(R.drawable.ic_switch_c)
                    statusStr.set("账户停用")
                } else {
                    onLineStatus.set(R.drawable.ic_switch_o)
                    statusStr.set("账户启用")
                }
            }
        }
    }

    val qrCodeClick = View.OnClickListener {
        if (accountEnable.get() == true) {
            openGalley.call()
        }
    }

    val bindClick = View.OnClickListener {
        if (accountBean?.status == -2) bind() else unBind()
    }

    fun initState() {
        val typeStr = when (type.get()) {
            BindInfoBean.ACCOUNT_TYPE_ALIPAY -> "支付宝"
            BindInfoBean.ACCOUNT_TYPE_WECHAT -> "微信"
            BindInfoBean.ACCOUNT_TYPE_ALL_IN_ONE1 -> "聚合码"
            else -> ""
        }
        if (type.get() in arrayOf(BindInfoBean.ACCOUNT_TYPE_ALIPAY,BindInfoBean.ACCOUNT_TYPE_WECHAT)) {
            accountType.set("${typeStr}昵称")
        }
        showAlipayAuthor.set(type.get() == BindInfoBean.ACCOUNT_TYPE_ALIPAY)
        if (accountBean?.status == -2) {
            canOption.set(false)
            accountEnable.set(true)
            showAlert.set(true)
            bindButton.set("确认绑定")
        } else {
            canOption.set(true)
            bindButton.set("解除绑定")
            account.set(accountBean?.account)
            accountEnable.set(false)
            showAlert.set(false)
            qrCode = accountBean?.qrcode
        }
    }

    fun bind() {
        val accountStr = account.get()?.trim()
        val typeStr = if (type.get() in arrayOf(BindInfoBean.ACCOUNT_TYPE_ALIPAY,BindInfoBean.ACCOUNT_TYPE_WECHAT)) "微信" else "支付宝"
        if (accountStr == null || accountStr.isEmpty()) {
            toast("请输入正确的${typeStr}昵称")
            return
        }
        if (qrCode == null || qrCode!!.isEmpty()) {
            toast("请选择正确的${typeStr}收款码")
            return
        }
        GlobalScope.launch(Dispatchers.Main) {
            val result = GlobalScope.async(Dispatchers.IO) {
                tryRun {
                    HttpClient.httpApi.bindAccount(accountStr, type.get()!!, qrCode!!, 1).execute()
                }
            }
            val body = result.await()?.body()
            if (body?.code == 0){
                toast("绑定成功")
                finish.call()
            }
        }
    }

    fun unBind() {
        val map = mapOf(
            Constant.ROUTE_PARAMS_KEY.SMS_TITLE to "手机验证",
            Constant.ROUTE_PARAMS_KEY.SMS_BUTTON to "确定解除绑定",
            Constant.ROUTE_PARAMS_KEY.SMS_ACTION to Constant.ROUTE_PARAMS_KEY.ACTION_UNBIND_WX_OR_ALIPAY,
            Constant.ROUTE_PARAMS_KEY.PARAM_ACCOUNT_TYPE to type.get()?.toString(),
            Constant.ROUTE_PARAMS_KEY.SMS_NEED_FINISH to true
        )
        go(RouterIndex.SEND_SMS,map)
    }

    override fun initial() {
        super.initial()
        if (accountBean?.status == 1) {
            statusStr.set("账户启用")
            onLineStatus.set(R.drawable.ic_switch_o)
        } else{
            statusStr.set("账户停用")
            onLineStatus.set(R.drawable.ic_switch_c)
        }
        type.set(accountBean?.type)
        alipayBindStatus.set(accountBean?.user_id != null&&accountBean?.user_id!!.isNotEmpty())
    }
}